package borge.web.teamspirit.client.page.shared.widgets;

import java.util.List;

import borge.web.teamspirit.client.data.News;
import borge.web.teamspirit.client.interfaces.PersistentData;
import borge.web.teamspirit.client.interfaces.ServerCallbackHandler;
import borge.web.teamspirit.client.interfaces.WidgetEventHandler;
import borge.web.teamspirit.client.interfaces.PersistentData.DataKey;
import borge.web.teamspirit.client.servercomm.DBQuery;
import borge.web.teamspirit.client.servercomm.DBQueryResults;
import borge.web.teamspirit.client.servercomm.ServerComm;
import borge.web.teamspirit.client.servercomm.DBQueryResults.Result;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ShowNewsWidget extends ShowDataWidget {
	
	private String iParentKey;
	
	private VerticalPanel iPanel;
	private FlexTable iTable;
	
	private List<PersistentData> iNews;
	
	public ShowNewsWidget(WidgetEventHandler aHandler){
		super(aHandler);

		iPanel = new VerticalPanel();
		iTable = new FlexTable();
		iPanel.add(iTable);
		
		initWidget(iPanel);
		
	}
	
	private void createDataTable(){
		
		int row = 0, column = 0;
		
		for(PersistentData pd : iNews){
			News news = (News)pd;
			iTable.setText(row++, column, news.getTitle());
			iTable.setText(row++, column, news.getPosterName());
			iTable.setText(row++, column, news.getDate().toString());
			iTable.setText(row++, column, news.getText());
			iTable.setText(row++, column, "---");
		}
		
	}

	@Override
	public void requestServerData(ServerCallbackHandler aHandler) {

		DBQuery query = new DBQuery(DataKey.NEWS, News.class.getName());
		query.addFilter("iParentKey", DBQuery.EQUALS, "parentKey", "String", iParentKey, null);
		ServerComm.getObjectList(query, aHandler);
		
	}

	@Override
	public boolean needsUpdate(String aData) {
		
		if(iParentKey == null || !iParentKey.equals(aData)){
			iParentKey = aData;
			return true;
		}
		
		return false;
	}

	@Override
	public void populateData(DBQueryResults results) {

		Result result = results.getResult(DataKey.NEWS);
		iNews = result.getResultList();
		
		createDataTable();
	}

}
